package servlet;

import dao.UserDao;
import entity.User;
import utils.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private UserDao userDao = new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("userName");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String sex = request.getParameter("sex");
        String pieceName = request.getParameter("pieceName");
        String phone = request.getParameter("phone");
        String province = request.getParameter("province");
        String district = request.getParameter("district");
        String detailAddress = request.getParameter("detailAddress");


        if (!password.equals(confirmPassword)) {
            response.sendRedirect("registerUser.jsp?error=1");
            return;
        }

        if (userDao.userExists(username)) {
            response.sendRedirect("registerUser.jsp?error=1");
            return;
        }

        User user = new User();
        user.setUserName(username);
        user.setPassword(password);
        user.setSex(sex);
        user.setPeiceName(pieceName);
        user.setPhone(phone);
        user.setProvince(province);
        user.setDistrict(district);
        user.setDetailAddress(detailAddress);

        if (userDao.insertUser(user)) {
            response.sendRedirect("login.jsp");
        } else {
            response.sendRedirect("registerUser.jsp?error=1");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}